package main.controller;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Aggregates;
import main.*;
import main.database.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import static com.mongodb.client.model.Filters.eq;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
public class MainPageController {
    @GetMapping("/")
    public String getMainPage(ModelMap modelMap, HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isExist = AccountHelper.isExistFromUUID(uuid);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

        String user = "";
        if (isExist) {
            user = uuid;
        }

        StatisticHelper.addMainPageAccess(uuid, NetworkHelper.getIPAddress(request), TimeHelper.getFormattedNowString(), UserAgentHelper.getUserAgent(request));

        List<String[]> artileList = ArticleHelper.findArtileListFromTime(9);
        List<String[]> authorList = AuthorHelper.findAuthorListFromTime(9);
        List<String[]> topArticleList = findWhatToRead();
        List<String[]> audioList = AudioHelper.findRecordsBaseOnTime(10);

        long unread = 0;
        if (isExist) {
            unread = NotifyHelper.countUnreadNotify(uuid);
        }

        modelMap.put("siteName", GlobalConfig.siteName);
        modelMap.put("displayGongZhongHao", GlobalConfig.displayGongZhongHao);
        modelMap.put("isLogin", isExist);
        modelMap.put("isAdmin", isAdmin);
        modelMap.put("unread", unread);
        modelMap.put("articleList", artileList);
        modelMap.put("authorList", authorList);
        modelMap.put("topArticleList", topArticleList);
        modelMap.put("audioList", audioList);
        modelMap.put("year2year", TimeHelper.getFormattedYear2Year());

        return "mainPage";
    }

    private List<String[]> findWhatToRead() {
        List<String[]> resultList = new ArrayList<>();

        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);
        Bson sortMethod = new Document("score", -1);
        FindIterable<Document> findIterable = collection.find().sort(sortMethod).limit(3);
        MongoCursor<Document> cursor = findIterable.iterator();

        //综合前3名
        Integer index = 1;
        while(cursor.hasNext()) {
            Document doc = cursor.next();

            String[] values = new String[8];
            values[0] = doc.get("title").toString();
            values[1] = "综合";
            values[2] = (index++).toString();
            values[3] = TimeHelper.getFormattedNowString();
            values[4] = ScoreHelper.getFormattedSecretScore((double) doc.get("score"));
            values[5] = doc.get("catlog").toString();
            values[6] = AuthorHelper.getAuthorNameFromId(doc.get("author").toString());
            values[7] = doc.get("_id").toString();
            resultList.add(values);
        }
        cursor.close();

        //随机3个catlog准备
        collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfRootCatlog);
        int count = (int) collection.countDocuments();
        AggregateIterable<Document> aggregateIterable = collection.aggregate(Arrays.asList(Aggregates.sample(count)));
        cursor = aggregateIterable.iterator();

        String[] catlogs = new String[count];
        index = 0;
        while(cursor.hasNext()) {
            catlogs[index++] = cursor.next().get("name").toString();
        }
        cursor.close();

        //准备好的catlog中，随机的三个名次
        collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);

        // first one
        for (int i = 0; i < count; ++i) {
            index = new Random().nextInt(9) + 1;
            Bson filter = eq("rootcatlog", catlogs[i]);
            findIterable = collection.find(filter).sort(sortMethod).skip(index).limit(1);
            cursor = findIterable.iterator();

            if (cursor.hasNext()) {
                Document doc = cursor.next();

                String[] values = new String[8];
                values[0] = doc.get("title").toString();
                values[1] = doc.get("rootcatlog").toString();
                values[2] = (++index).toString();
                values[3] = TimeHelper.getFormattedNowString();
                values[4] = ScoreHelper.getFormattedSecretScore((double) doc.get("score"));
                values[5] = doc.get("catlog").toString();
                values[6] = AuthorHelper.getAuthorNameFromId(doc.get("author").toString());
                values[7] = doc.get("_id").toString();
                resultList.add(values);
            }
            cursor.close();
        }

        return resultList;
    }
}
